import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/alert_business/mine/vip_level_dialog.dart';
import 'package:xvideos/alert_business/normal_alert_style.dart';
import 'package:xvideos/config/config.dart';
import 'package:xvideos/hj_model/upload_video_model.dart';
import 'package:xvideos/hj_page/mine_business/ai/mode/AiModList.dart';
import 'package:xvideos/hj_page/mine_business/ai/widget/ai_mod_widgets.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/coupon_model.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_utils/api_service/ai_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/tools_base/file_upload/file_upload_tool.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/LoadingHelper.dart';
import 'package:xvideos/tools_base/loading/loading_alert_widget.dart';

import 'ai_coupon_bottom.dart';

enum AIFunctionType {
  autoStrip, //智能脱衣
  manualStrip, //手动脱衣
  videoChangeFace, //视频换脸
  imageChangeFace, //图片换脸
}

instanceController(AiModList? model, AIFunctionType type) {
  switch (type) {
    //智能脱衣
    case AIFunctionType.autoStrip:
      return AIStripLogic(model, autoStrip: true);
    //手动脱衣
    case AIFunctionType.manualStrip:
      return AIStripLogic(model, autoStrip: false);
    //视频换脸
    case AIFunctionType.videoChangeFace:
      return AIVideoChangeFaceLogic(model);
    //图片换脸
    case AIFunctionType.imageChangeFace:
      return AIImageChangeFaceLogic(model);
    default:
      return AIStripLogic(model);
  }
}

abstract class AIFunctionBaseLogic extends GetxController {
  final uploadModel = UploadVideoModel();
  AiModList? rawDataModel;
  final ratio = 168 / 95;
  final dataSource = [];
  final spaceW = 7.0;
  final spaceH = 10.0;
  final crossAxisCount = 2;
  final hint = '您还不是VIP无法使用AI脱衣';
  bool? autoStrip = false; //是否是自动脱衣

  AIFunctionBaseLogic(
    this.rawDataModel, {
    this.autoStrip = false,
  });

  //检查免费次数
  bool checkFreeTimesEnable(int price) {
    if ((globalStore.wallet?.amount ?? 0) < (int.tryParse(Config.aiUndressPrice ?? "0") ?? 0) &&
        (globalStore.wallet?.todayAiFreeTimes ?? 0) <= 0) {
      showVipLevelDialog("当前免费次数不足或金币不足", buttonTitle: '我知道了', vipEvent: () => Get.back());
      return false;
    }
    return true;
  }

  ///提交 默认为脱衣
  submitAiImage() async {
    if (presaleProvider.isOpen && presaleProvider.hasLimit && (presaleProvider.remain?.todayAiUndressCount ?? 0) > 0) {
      presaleProvider.remain?.todayAiUndressCount = (presaleProvider.remain?.todayAiUndressCount ?? 0) - 1;
    } else {
      /// 当日免费次数
      if (!globalStore.isVIP()) {
        showVipLevelDialog(hint);
        return;
      }
      final price = int.tryParse(Config.aiUndressPrice ?? '') ?? 0;
      if (!checkFreeTimesEnable(price)) return;
    }
    aiRemoveCloth();
  }

  //ai脱衣操作
  aiRemoveCloth() async {
    if (uploadModel.localPicList.isEmpty) {
      showConfirm(title: "提示", content: "请选择图片");
      return;
    }
    List<String> picList = [];
    //1.添加本地图片路径
    picList.addAll(uploadModel.localPicList);

    LoadingAlertWidget.show(Get.context!);
    try {
      //1.上传路径图片
      LoadingAlertWidget.showExchangeTitle("正在上传图片...");
      var uploadImgArr = await FileUpLoadTool().uploadImageList(picList, proCallback: (tIndex, tAll, proCount, totalCount) {
        LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
      });
      List<String> imageArr = [];
      if (uploadImgArr?.isNotEmpty == true) {
        imageArr = uploadImgArr!.map((e) => e.coverImg ?? "").toList();
      }

      //2.添加涂鸦数据
      List<String>? dataImageArr;
      if (uploadModel.graffitiModel != null && uploadModel.graffitiModel!.graffitiData != null) {
        LoadingAlertWidget.showExchangeTitle("正在上传图片...");
        var resp = await FileUpLoadTool().uploadImageData(uploadModel.graffitiModel!.graffitiData!);

        if (resp != null) {
          dataImageArr ??= [];
          dataImageArr.add(resp.coverImg ?? '');
        }
      }

      LoadingAlertWidget.showExchangeTitle("正在更新数据...");

      final result = await AIService.aiGenerate(imageArr, maskPic: dataImageArr);
      LoadingAlertWidget.cancel(Get.context!);

      if (result) {
        showToast("提交成功～");
        uploadModel.localPicList.clear();
        uploadModel.selectedTagIdList.clear();
        uploadModel.updateStripModel(null); //清除涂鸦数据
        globalStore.refreshWallet();
        update();
      } else {
        showToast("提交失败");
      }
    } on DioException catch (e) {
      showToast(e.message.toString());
    } catch (e) {
      showToast(e.toString());
    } finally {
      LoadingAlertWidget.cancel(Get.context!);
    }
  }

  Widget instanceChild(int index) => throw UnimplementedError();
}

// 脱衣
class AIStripLogic extends AIFunctionBaseLogic {
  double get aspectRatio => 408 / 310;

  AIStripLogic(super.rawDataModel, {super.autoStrip});

  @override
  void onReady() {
    super.onReady();
    loadData();
  }

  //获取脱衣模版
  loadData() async {
    rawDataModel = await AIService.getAIModelList();
    update();
  }
}

// 视频换脸
class AIVideoChangeFaceLogic extends AIFunctionBaseLogic {
  AIVideoChangeFaceLogic(super.rawDataModel);

  @override
  String get hint => '您还不是VIP无法使用视频换脸';

  @override
  void onInit() {
    super.onInit();
    dataSource.addAll(rawDataModel?.aiChangeFaceVideoMod ?? []);
  }

  @override
  void onReady() {
    super.onReady();
  }

  loadData() async {
    AIService.getAIChangeFaceList(type: 0, categoryId: '');
  }

  @override
  Widget instanceChild(int index) {
    return AIViodeoChangeFaceModView(dataSource[index]);
  }
}

// 图片换脸
class AIImageChangeFaceLogic extends AIFunctionBaseLogic {
  AIImageChangeFaceLogic(super.rawDataModel);

  @override
  void onInit() {
    super.onInit();
    dataSource.addAll(rawDataModel?.aiChangeFaceMod ?? []);
  }

  @override
  String get hint => '您还不是VIP无法使用图片换脸';

  @override
  double get ratio => 111 / 177;

  @override
  double get spaceW => 5;

  @override
  int get crossAxisCount => 3;

  @override
  Widget instanceChild(int index) {
    return AIImageChangeFaceModView(dataSource[index]);
  }
}

// 换脸详情
class AIChangeFaceDetailModLogic extends AIFunctionBaseLogic {
  AIChangeFaceDetailModLogic(super.rawDataModel, {required this.modModel});

  final TemplateModel modModel; // 换脸模版
  bool get isChangeVideo => modModel.moduleType == 1; // 是否为视频
  AICouponModel? coupon; //折扣券

  @override
  String get hint => '您还不是充值VIP无法使用AI换脸';

  int realCostCoin() { // 视频/图片换脸 都用modModel里的价格
    return globalStore.isVIP() ? (modModel.vipCoin ?? 0) : (modModel.coin ?? 0);
    if (isChangeVideo) return globalStore.isVIP() ? (modModel.vipCoin ?? 0) : (modModel.coin ?? 0);
    return int.parse((Config.aiChangeFaceImgPrice ?? '0'));
  }

  @override
  submitAiImage() async {
    if (presaleProvider.isOpen && presaleProvider.hasLimit && (presaleProvider.remain?.todayAiUndressCount ?? 0) > 0 && !isChangeVideo) {
      presaleProvider.remain?.todayAiUndressCount = (presaleProvider.remain?.todayAiUndressCount ?? 0) - 1;
    } else {
      // if (!globalStore.isVIP()) {
      //   showVipLevelDialog(hint);
      //   return;
      // }
      final price_ = realCostCoin(); //获取真实价格
      if (!isChangeVideo) {
        if (!checkFreeTimesEnable(price_)) return;
      }
      if (uploadModel.localPicList.length == 0) {
        showConfirm(title: "提示", content: "请选择图片");
        return;
      }
    }
    changeImgAction();
  }

  showCoupon() async {
    AICouponModel? model = await Get.bottomSheet(AICouponsBottom());
    if (model != null) {
      coupon = model;
      update();
    }
  }

  changeImgAction() async {
    LoadingAlertWidget.show(Get.context!);
    try {} catch (e) {}
    List<String> picList = uploadModel.localPicList;
    try {
      LoadingAlertWidget.showExchangeTitle("正在上传图片...");
      final netImages = await FileUpLoadTool().uploadImageList(picList, proCallback: (tIndex, tAll, proCount, totalCount) {
        LoadingAlertWidget.showExchangeTitle("正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%");
      });

      final imageUrls = netImages?.map((e) => e.coverImg ?? '').toList();
      LoadingAlertWidget.showExchangeTitle("正在更新数据...");
      bool result;
      if (isChangeVideo) {
        //视频换脸
        result = await AIService.aiFaceGenerate(
          imageUrls,
          modModel.id,
          coupon?.id,
        );
      } else {
        //图片换脸
        result = await AIService.aiFacegenerateByPicture(
          imageUrls?.firstOrNull ?? '',
          modModel.id ?? '',
        );
      }
      LoadingAlertWidget.cancel(Get.context!);

      if (result) {
        showToast("提交成功～");
        uploadModel.localPicList.clear();
        uploadModel.selectedTagIdList.clear();
        coupon = null;
        globalStore.refreshWallet();
        update();
      } else {
        showToast("提交失败");
      }
    } on DioError catch (e) {
      LoadingHelper.dismissLoading();
    } catch (e) {
      LoadingHelper.dismissLoading();
    }
  }
}
